package org.csu.linkgame.controller;

import com.leewyatt.rxcontrols.animation.carousel.AnimFade;
import com.leewyatt.rxcontrols.controls.RXAvatar;
import com.leewyatt.rxcontrols.controls.RXCarousel;
import com.leewyatt.rxcontrols.controls.RXFillButton;
import com.leewyatt.rxcontrols.enums.DisplayMode;
import com.leewyatt.rxcontrols.pane.RXCarouselPane;
import de.felixroske.jfxsupport.FXMLController;
import javafx.animation.Animation;
import javafx.animation.Interpolator;
import javafx.animation.PathTransition;
import javafx.animation.TranslateTransition;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import org.csu.linkgame.LinkGameApplication;
import org.csu.linkgame.domain.User;
import org.csu.linkgame.service.ClassForDoubleGame.dgServiceImpl;
import org.csu.linkgame.utils.AlertView;
import org.csu.linkgame.utils.ServiceUtil;
import org.csu.linkgame.utils.WSClient;
import org.csu.linkgame.view.DoubleView;
import org.csu.linkgame.view.RankView;
import org.csu.linkgame.view.SoloView;
import org.pan.decorate.StageDecorate;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Optional;
import java.util.ResourceBundle;

@FXMLController
public class TextController implements Initializable {
    @FXML
    public RXFillButton signOutButton;
    @FXML
    public RXCarousel sceneryCarousel;
    @FXML
    public RXAvatar avatar;
    @FXML
    private Label usernameLabel;
    @FXML
    private RXFillButton soloGameButton;
    @FXML
    private RXFillButton doubleGameButton;
    @FXML
    private RXFillButton rankListButton;
    @FXML
    private RXFillButton gameHistoryButton;
    User user;

    AlertView alertView;
    dgServiceImpl dgCanvas;
    @FXML
    private AnchorPane musicPane;
    @FXML
    private AnchorPane chatPane;
    private TranslateTransition transitionShowMusic;
    private TranslateTransition transitionHideMusic;
    private TranslateTransition transitionShowChat;
    private TranslateTransition transitionHideChat;
    private Boolean isShowMusic=false;
    private Boolean isShowChat=false;

    String baseUrl = "http://orange-1312206514.cos.ap-guangzhou.myqcloud.com/images/";
    String userUrl = baseUrl + "test.jpg";
    Image image;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        musicPane.setTranslateX(600);
        chatPane.setTranslateX(600);

        initPanes();
        sceneryCarousel.setCarouselAnimation(new AnimFade());
        sceneryCarousel.setHoverPause(true);
        sceneryCarousel.setAutoSwitch(true);
        sceneryCarousel.setAnimationTime(Duration.millis(320));
        sceneryCarousel.setShowTime(Duration.millis(3000));
        sceneryCarousel.setArrowDisplayMode(DisplayMode.SHOW);
        sceneryCarousel.setNavDisplayMode(DisplayMode.SHOW);

        transitionShowMusic = new TranslateTransition();
        transitionShowMusic.setDuration(Duration.seconds(0.5));
        transitionShowMusic.setNode(musicPane);
        transitionShowMusic.setFromX(600);
        transitionShowMusic.setToX(0);
        transitionShowMusic.setInterpolator(Interpolator.EASE_BOTH);

        transitionHideMusic = new TranslateTransition();
        transitionHideMusic.setDuration(Duration.seconds(0.5));
        transitionHideMusic.setNode(musicPane);
        transitionHideMusic.setFromX(0);
        transitionHideMusic.setToX(600);
        transitionHideMusic.setInterpolator(Interpolator.EASE_BOTH);

        transitionShowChat = new TranslateTransition();
        transitionShowChat.setDuration(Duration.seconds(0.5));
        transitionShowChat.setNode(chatPane);
        transitionShowChat.setFromX(600);
        transitionShowChat.setToX(0);
        transitionShowChat.setInterpolator(Interpolator.EASE_BOTH);

        transitionHideChat = new TranslateTransition();
        transitionHideChat.setDuration(Duration.seconds(0.5));
        transitionHideChat.setNode(chatPane);
        transitionHideChat.setFromX(0);
        transitionHideChat.setToX(600);
        transitionHideChat.setInterpolator(Interpolator.EASE_BOTH);

        image = new Image(userUrl);
        avatar.setImage(image);
    }

    private void initPanes() {
        String[] str = {"莺飞草长", "风雨兼程", "手捧星光", "日暮不赏"};//
        // sp.setCarouselAnimation(new AnimHorMove(true));
        final Duration millis = Duration.millis(3000);
        ArrayList<RXCarouselPane> panes = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            ImageView iv = new ImageView(getClass().getResource("../scenery/" + (i + 1) + ".png").toExternalForm());
            Label label = new Label(str[i]);
            label.setPrefSize(100, 30);
            label.setStyle("-fx-alignment: center;-fx-background-color:black;-fx-text-fill: white;-fx-font-size: 20");
            //label.setVisible(false);
            label.setTranslateY(100);
            StackPane stackPane = new StackPane(iv,label);
            RXCarouselPane p1 = new RXCarouselPane(stackPane);
            //RXCarouselPane 是继承自 BorderPane的
            //p1.setCenter(stackPane);

            //p1.setText(String.valueOf(i+1));
            p1.setOnClosed(event -> {
                //System.out.println("触发了已经关闭");
                event.consume();
            });
            p1.setOnOpening(event -> {
                // System.out.println("触发了正在打开");
                event.consume();

            });
            TranslateTransition ttOnOpened = new TranslateTransition(Duration.millis(1000), label);
            ttOnOpened.setFromY(100);
            ttOnOpened.setToY(0);
            p1.setOnOpened(event -> {
                //System.out.println("触发了已经打开");

                ttOnOpened.play();
                event.consume();
            });
            TranslateTransition ttOnClosing = new TranslateTransition(Duration.millis(1000), label);
            ttOnClosing.setFromY(0);
            ttOnClosing.setToY(100);
            p1.setOnClosing(event -> {
                //System.out.println("触发了正在关闭");
                ttOnClosing.play();
                event.consume();
            });
            panes.add(p1);
            p1.setPrefSize(650, 353);
        }
        sceneryCarousel.setPaneList(panes);
    }
    public void showMusicPane(){
        if (!isShowMusic){
            if (isShowChat){
                transitionHideChat.play();
                isShowChat=false;
            }
            transitionShowMusic.play();
            isShowMusic=true;
        }
        else {
            transitionHideMusic.play();
            isShowMusic=false;
        }
    }
    public void showChatPane(){
        if (!isShowChat){
            if (isShowMusic){
                transitionHideMusic.play();
                isShowMusic=false;
            }
            transitionShowChat.play();
            isShowChat=true;
        }
        else {
            transitionHideChat.play();
            isShowChat=false;
        }
    }

    public void setUser(User user) {
        this.user = user;
        usernameLabel.setText(user.getUsername());
        userUrl = baseUrl + user.getUsername() + ".jpg";
        image = new Image(userUrl);
    }
    public void setDgCanvas(dgServiceImpl dgCanvas){
        this.dgCanvas = dgCanvas;
    }

    public void onSoloGameButtonClicked(MouseEvent mouseEvent) throws Exception {
        // 打开单人模式界面
        FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/solo.fxml"));
        Stage stage = new Stage(StageStyle.DECORATED);
        stage.setScene(new Scene(loader.load()));
        SoloViewController soloViewController = loader.getController();
        soloViewController.setUser(user);
        soloViewController.setUserInfoImage();
        ServiceUtil.serviceUtil.logService.insertLog(user.getUsername() + "打开了单人游戏界面");
        stage.show();
    }

    public void onDoubleGameButtonClicked(MouseEvent mouseEvent) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/double.fxml"));
        Stage stage = new Stage(StageStyle.DECORATED);
        stage.setScene(new Scene(loader.load()));

        DoubleViewController doubleViewController = loader.getController();
        doubleViewController.setUser(user);
        //System.out.println("Button" + dgCanvas);
        doubleViewController.setUserInfoImage();
        doubleViewController.setDgCanvas(dgCanvas);
        ServiceUtil.serviceUtil.logService.insertLog(user.getUsername() + "打开了多人联机界面");
        stage.show();
    }

    public void onRankGameButtonClicked(MouseEvent mouseEvent) throws Exception {
        // 打开排行榜界面
        FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/rank.fxml"));
        Stage stage = new Stage(StageStyle.DECORATED);
        stage.setScene(new Scene(loader.load()));

        RankViewController rankViewController = loader.getController();
        rankViewController.initializeData();
        ServiceUtil.serviceUtil.logService.insertLog(user.getUsername() + "打开了排行榜界面");
        stage.show();
    }

    public void onGameHistoryButtonClicked(MouseEvent mouseEvent) throws Exception {
        // 打开战绩界面
        FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/history.fxml"));
        Stage stage = new Stage(StageStyle.DECORATED);
        stage.setScene(new Scene(loader.load()));

        HistoryViewController historyViewController = loader.getController();
        historyViewController.setUser(user);
        historyViewController.initializeData();
        ServiceUtil.serviceUtil.logService.insertLog(user.getUsername() + "打开了战绩界面");
        stage.show();
    }

    public void backToLoginView(ActionEvent event) throws IOException {
        alertView = new AlertView(Alert.AlertType.CONFIRMATION);
        alertView.setTitle("管理员请确认！");
        alertView.setHeaderText("你将要退出登录！");
        alertView.setContentText("是否退出？请选择！！！");
        Optional<ButtonType> result = alertView.showAndWait();
        if (result.get() == ButtonType.OK) {
            // 客户端下线
            ServiceUtil.serviceUtil.logService.insertLog(user.getUsername() + "退出登录");
            WSClient.getInstance().close();
            Stage adminStage = (Stage) signOutButton.getScene().getWindow();
            adminStage.close();

            FXMLLoader loader = new FXMLLoader(getClass().getResource("../view/login.fxml"));
            Parent root = loader.load();
            Stage stage = new Stage(StageStyle.DECORATED);
            stage.initModality(Modality.WINDOW_MODAL);
            stage.setScene(new Scene(root));
            StageDecorate.decorate(stage,root);
            stage.setTitle("超级连连看٩( 'ω' )و ");
            stage.getIcons().add(new Image("/org/csu/linkgame/images/icon.png"));
            stage.show();
        }
    }


}
